from datetime import datetime
from io import BytesIO
import json
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from yida_app_service.views import get_xm_client
import base64
import qrcode
from django.shortcuts import render
from reportservice.helpers import ApiResponse
from yida_app_service.sanhe.xm_cloud_config import XmCloudClient
from yida_app_service.xu_cloud_client import XmCloudBaseClient
from .yida_config import YidaClient
yida_client = YidaClient()
admin_user_id = "014835331124251186"
company_name = "sanhe"

@csrf_exempt
@require_http_methods(["GET"])
def create_report(request):
    report_inst_id = request.GET.get("report_inst_id")
    report_result = yida_client.get_form_items_by_ids(form_uuid="FORM-4CB2D67BC0A34549A2DCDAABD7E0642F43NR",form_inst_id=report_inst_id,userId=admin_user_id)
    report_form:dict = report_result[0].form_data
    wt_inst = json.loads(json.loads(report_form.get("associationFormField_lzw5dy60_id")))
    commission_result = yida_client.get_form_items_by_ids(wt_inst[0].get('formUuid'),wt_inst[0].get("instanceId"),admin_user_id)
    commission_form = commission_result[0].form_data
    render_data = {
        "结论状态":report_form.get("selectField_lzw5dy65"),
        "委托编号":commission_form.get("textField_lzs0x0b9"),
        "委托单位":commission_form.get("textField_lzs0x0ba"),
        "委托日期":commission_form.get("dateField_lzweua3h"),
        "检测时间":report_form.get("dateField_lzw5dy6a"),
        "检测结束时间":report_form.get("dateField_lzw5dy6b"),
        
    }
    # associationFormField_lzs0x0b3_id
    detection_project_inst = json.loads(json.loads(commission_form.get("associationFormField_lzs0x0b3_id")))
    detection_project_result = yida_client.get_form_items_by_ids(detection_project_inst[0].get('formUuid'),detection_project_inst[0].get("instanceId"),admin_user_id)
    detection_project_form = detection_project_result[0].form_data
    xm_client = XmCloudClient()
    create_report_result = xm_client.create_special_report_record(model_ids=[item.get("textField_lzw52z0s") for item in detection_project_form['tableField_lzw52z0p']],
                                           name=commission_form.get("textField_lzs0x0b9"),
                                           pub_render_data=render_data)
    if create_report_result.get("code") == 200:
        return ApiResponse.success(create_report_result.get("data"))
    else:
        return ApiResponse.fail(create_report_result.get("message"))

   
# 使用宜搭数据在平台创建工程并生成二维码去创建委托
@csrf_exempt
@require_http_methods(["GET"])
def get_uuid_QRcode_by_project(request):
    formInstId = request.GET.get('formInstId')
    form_uuid = 'FORM-7FD4E6718FBE47F7BCE17161009EA0B6EF4K'
    yida_instance = yida_client.get_form_items_by_ids(form_uuid, formInstId, admin_user_id)
    print(formInstId,yida_instance)

    body = {
        "project_number": yida_instance[0].form_data["textField_m023zgi3"],  # 项目编号
        "registration_date": yida_instance[0].form_data["dateField_lzrzlfjq"],  # 登记日期
        "project_name": yida_instance[0].form_data["textField_lzrzlfjr"],  # 项目名称
        "project_address": yida_instance[0].form_data["textareaField_lzxvw0ez"],  # 项目地址
        "callback_url": "sanhe"
    }
    XmCloudClient = get_xm_client('sanhe')
    xm_client:XmCloudBaseClient = XmCloudClient()
    response = xm_client.create_project(body)
    print(response)
    
    if response.get('code') == 200:
        project_token = response.get('data').get('project_token')
        print('project_token--->',project_token)
        qr_url = f'http://report.zjxmyq.cn/commission/create?uuid={project_token}'
        # Generate QR code
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )
        qr.add_data(qr_url)
        qr.make(fit=True)
        img = qr.make_image(fill='black', back_color='white')
        # Convert image to base64
        buffered = BytesIO()
        img.save(buffered, format="PNG")
        img_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
        
        # Pass base64 image to template
        context = {
            'qrcode': f"data:image/png;base64,{img_base64}",
            'url': qr_url
        }
        return render(request, 'qrcode_by_project.html', context)
    else:
        return ApiResponse.fail('失败')


# 在宜搭中创建委托   
@csrf_exempt
@require_http_methods(["POST"])
def create_commission_yida(request):
    req_data = json.loads(request.body)
    commision_info = req_data.get('commision_info')
    # print('commision_info--->',commision_info)
    # yida_data = {}
    project_data = yida_client.get_form_data_by_search_field(
        'FORM-7FD4E6718FBE47F7BCE17161009EA0B6EF4K',
        admin_user_id,
        {
            "textField_lzrzlfjr":req_data.get("project_name")
        }
    )
    exam_data = yida_client.get_form_data_by_search_field(
        'FORM-1B6FEE1A505D4852A1A0A75851F0E975U1QR',
        admin_user_id,
        {
            "textField_lzw448v2":req_data.get("exam_name")[1]
        }
    )
    # 委托代码
    contracts_code = exam_data[0].form_data['textField_lzw448v6']
    print('委托代码--->',contracts_code)
    
    match_field_data = {
      "textField_lzxv9z4j": contracts_code
    }
    # 流水号
    serial_number = gen_serial_number(
        'FORM-C29D12FF77294235BE99AD8FEF5ABADA53E0',
        match_field_data,
        'numberField_lzxv9z4i'
    )
    print('流水号--->',serial_number)
    contracts_report = contracts_code + str(datetime.now().year) + f"{serial_number:05}"
    print('委托编号--->',contracts_report)
    # print('exam_data-->',exam_data[0].form_instance_id,exam_data[0].form_data['textField_lvhqtamr'])
    # return ApiResponse.success('成功')
    # 资质类别
    label = req_data.get("qualification_name")

    yida_client.create_form_data(
        'FORM-C29D12FF77294235BE99AD8FEF5ABADA53E0',
        admin_user_id,
        {
            "associationFormField_lzs0x0am":[
              {
                "appType": 'APP_RXK38EZXPT61V4YJLUD6', 
                "formType": 'receipt',
                "formUuid": 'FORM-7FD4E6718FBE47F7BCE17161009EA0B6EF4K',
                "instanceId": project_data[0].form_instance_id,
                "title": project_data[0].form_data["textField_lzrzlfjr"],
              },  
            ],
            "selectField_lvhhb44e": label,  #资质类别
            "selectField_lzw4hk6z": req_data.get("exam_name")[0],  #检测大类
            "associationFormField_lzs0x0b3": [{
                "appType": 'APP_RXK38EZXPT61V4YJLUD6', 
                "formType": 'receipt',
                "formUuid": 'FORM-1B6FEE1A505D4852A1A0A75851F0E975U1QR',
                "instanceId": exam_data[0].form_instance_id,
                "title": exam_data[0].form_data["textField_lzw448v2"]
              }],  #检测项目
            "textField_lzxv9z4j": contracts_code,  #委托代码
            "numberField_lzxv9z4i": serial_number,  #委托流水号
            "textField_lzs0x0b9": contracts_report,  #委托编号
            "employeeField_lzs0x0b4": ["300208014636253254"],  #编制人  
            "radioField_m025klsq": "见证取样",
            "selectField_lzwfu6pg": "单份"
        }
    )
    # 查询委托数据
    commission_data = yida_client.get_form_data_by_search_field(
        'FORM-C29D12FF77294235BE99AD8FEF5ABADA53E0',
        admin_user_id,
        {
            "textField_lzs0x0b9":contracts_report
        }
    )
    # print('commission_data--->',commission_data[0].form_instance_id)
    for index, sample in enumerate(commision_info):
        # 检测参数列表
        tableDataList = []
        for item in sample['tableData']:
            tableData = {}
            tableData["selectField_lzuvjio4"] = item["parameter_term"],  # 参数小项/检测参数组
            # tableData["textField_lx9ssfuj"] = item["detection_standard"],  # 检测标准
            tableData["numberField_lzuzy7z3"] = item["cost"],  # 小计
            tableDataList.append(tableData)
        print('------>',req_data.get("qualification_id"))
        yida_client.create_form_data(
            'FORM-D8F0B63402B1481BA4F7E8F4E6214E833WHA',
            admin_user_id,
            {
                "associationFormField_lzuvjinv":[
                  {
                    "appType": 'APP_RXK38EZXPT61V4YJLUD6', 
                    "formType": 'receipt',
                    "formUuid": 'FORM-C29D12FF77294235BE99AD8FEF5ABADA53E0',
                    "instanceId": commission_data[0].form_instance_id,
                    "title": commission_data[0].form_data["textField_lzuvzaex"],
                  },  
                ],
                "tableField_lzuvjio2": tableDataList,  #检测参数
                "textField_lzwdkwlk":contracts_report,  #委托编号
                "serialNumberField_lzuvjiny":contracts_report+'-'+str(index+1),  #样品编号
                "textField_lzwdkwlg":label,  #资质类别
                "textField_lzuvjinz":req_data.get("exam_name")[0],  #检测大类
                "textField_lzuvjio0":req_data.get("exam_name")[1],  #检测项目
            }
        )
    return ApiResponse.success(data=contracts_report, message='成功')

def gen_serial_number(form_uuid,match_field_data,sn_field):
    try:
        if isinstance(match_field_data,list):
            match_field_data = match_field_data + [{"key":sn_field,"value":"","type":"DOUBLE","operator":"is_not","componentName":"NumberField"}]
        result = yida_client.get_form_data_by_search_field(form_uuid=form_uuid,
                                                  userId=admin_user_id,
                                                  search_field=match_field_data,
                                                  page_size=5,
                                                  dynamic_order={sn_field:"-"})
        if result:
            serial_number = result[0].form_data.get(sn_field,0)+1
            return serial_number
        elif len(result) == 0:
            return 1
    except Exception as err:
        return 0
 
    
    
@csrf_exempt
@require_http_methods(["GET"])
def batch_new_sample(request):
    sample_id=request.GET.get("sample_id")
    sample_result = yida_client.get_all_form_data_by_search_field("FORM-D8F0B63402B1481BA4F7E8F4E6214E833WHA",
                                                                    admin_user_id,
                                                                    search_field=[
                                                                        {
                                                                            "type": "NumberField ",
                                                                            "operator": "eq",
                                                                            "componentName": "NumberField ",
                                                                            "key": "serialNumberField_lzuvjiny",
                                                                            "value": sample_id
                                                                        }
                                                                    ])
    print(sample_result[0].form_data)
    return 1
    # total = results[0].form_data["numberField_lzuzy7z5"] 
    for i in range(total-1):
        yida_client.create_form_data(
            'FORM-D8F0B63402B1481BA4F7E8F4E6214E833WHA',
            admin_user_id,
            {
                "associationFormField_lzuvjinv":[
                {
                    "appType": 'APP_RXK38EZXPT61V4YJLUD6', 
                    "formType": 'receipt',
                    "formUuid": 'FORM-C29D12FF77294235BE99AD8FEF5ABADA53E0',
                    "instanceId": project_data[0].form_instance_id,
                    "title": project_data[0].form_data["textField_lzw4hk75"],
                    "subTitle": project_data[0].form_data["serialNumberField_lvkohqt7"],
                },  
                ],
                "selectField_lw94ok1x":req_data.get("signin_test_category"),  # 检测类别
                "selectField_lvhhb44e":label,  #资质类别
                "selectField_lwilh7eb":req_data.get("exam_item")[0],  #检测大类
                # "selectField_lvhhb44k":req_data.get("exam_item")[1],  #检测项目
                "associationFormField_lzqdcjum":[{
                    "appType": 'APP_LSBE7XYKW28JNYBTQLC0', 
                    "formType": 'receipt',
                    "formUuid": 'FORM-457D4A12C52F4A35A2778035F5B1A5C22QMM',
                    "instanceId": exam_data[0].form_instance_id,
                    "title": exam_data[0].form_data["textField_lvhqtamh"]
                }],  #检测项目
                "textField_lvkl30cy": datetime.now().year,  #年份
                "textField_lvj4vn5n": contracts_code,  #委托代码
                "numberField_lvkke7xm":serial_number,  #委托流水号
                "textField_lvhpww3e":contracts_report,  #委托编号
                "textField_lvj4vn58":contracts_report,  #报告编号
                "textField_lvhw5i6u":project_data[0].form_data["textField_lvhea611"],  #工程名称_
               
            })
    if result.get("code") == 200:
        return ApiResponse.success(result.get("data"))
    else:
        return ApiResponse.fail(result.get("message"))
    # for i in range(item.form_data[h*])